package com.aistar.controller;

import com.aistar.util.*;
import com.aistar.pojo.Customer;
import com.aistar.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;

@Controller
@RequestMapping("/customer")
public class CustomerController {
    private CustomerService customerService;

    @Autowired
    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    @RequestMapping("/login")
    @ResponseBody
    public ServerResponse login(String username, String password, Integer type, Integer userType, Integer remPassword, HttpServletRequest request, HttpServletResponse response) {
        ServerResponse serverResponse;
        if (1 == type) { // 手机号、邮箱 & 密码
            PrivateKey privateKey = RSAUtil.getPrivateKey();
            if (userType == 0) // 手机号
                serverResponse = customerService.getByTel(Long.valueOf(username));
            else // 邮箱
                serverResponse = customerService.getByEmail(username);
            if (serverResponse.getStatus() == 1) { // 有此用户，验证密码
                String passwordBlack = RSAUtil.decrypt(password, privateKey);
                Customer customer = (Customer) serverResponse.getData();
                String passwordCorrect = RSAUtil.decrypt(customer.getCustomerPassword(), privateKey);
                if (passwordCorrect != null && passwordCorrect.equals(passwordBlack)) {
                    if (remPassword != null && remPassword == 1) {
                        // 自动登录 创建cookie
                        Cookie autoLoginCookie = new Cookie("autoLogin", customer.getCustomerId() + "&" + customer.getCustomerPassword());
                        autoLoginCookie.setMaxAge(7 * 24 * 60 * 60); // cookie生命周期
                        autoLoginCookie.setPath(request.getContextPath()); // 保存路径
                        response.addCookie(autoLoginCookie); // response写入客户端
                    }
                    request.getSession().setAttribute("loginCustomer", customer); // 登录成功 用户存在
                    serverResponse = ServerResponse.getSuccess();
                } else
                    serverResponse = ServerResponse.getFailed(MessageUtil.USER_WRONG_PWD);
            }
        } else { // 手机号 & 验证码
            System.out.println("手机号，验证码登录");
            serverResponse = null;
        }
        return serverResponse;
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute("loginCustomer");
        Cookie killCookie = new Cookie("autoLogin", null);
        killCookie.setPath(request.getContextPath());
        killCookie.setMaxAge(0); // 立即删除
        response.addCookie(killCookie);
        return "redirect:/";
    }

    @RequestMapping("/add")
    @ResponseBody
    public ServerResponse register(Customer customer) {
        customer.setCustomerName(customer.getCustomerTel().toString());
        return customerService.add(customer);
    }

    @RequestMapping("/edit")
    public ModelAndView modify(Customer customer, HttpServletRequest request) {
        ServerResponse serverResponse = customerService.modify(customer);
        if (MessageUtil.STATUS_SUCCESS.equals(serverResponse.getStatus())) {
            Customer newCustomer = (Customer) customerService.getById(customer.getCustomerId()).getData();
            request.getSession().setAttribute("loginCustomer", newCustomer);
        }
        ModelAndView mav = new ModelAndView();
        mav.setViewName("redirect:/center/" + customer.getCustomerId() + "/basic");
        return mav;
    }

    @RequestMapping("/modifyHeadImg")
    public ModelAndView modifyHeadImg(MultipartFile file, Integer id) {
        String url = QiniuUtil.upload(file);
        Customer customer = new Customer();
        customer.setCustomerId(id);
        customer.setCustomerHeadImg(url);
        customerService.modify(customer);
        ModelAndView mav = new ModelAndView();
        mav.setViewName("redirect:/center/" + id + "/basic");
        return mav;
    }

    @RequestMapping("/getCode")
    @ResponseBody
    public ServerResponse getCode(Long custTelno) {
        // 数据库中查看手机号是否已经注册
        ServerResponse serverResponse = customerService.getByTel(custTelno);
        ServerResponse result;
        if (serverResponse.getStatus() != 1) {
            // 失败 - 用户不存在，可以创建
            // 获取验证码 - 调用短信接口
            // String code =  GetMessageCode.getCode(telnoStr);
            //String code = "666666";
            String code = SmsUtil.getSms(custTelno+"");
            result = ServerResponse.getSuccess(code);
        } else // 成功 - 用户已经存在
            result = ServerResponse.getFailed("用户已存在，请前往登录页面");
        return result;
    }
}
